package cn.zhuwj.autodiscovery.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @author zhuwj.cn
 */
public class NetUtils {

    public static String getRealIpv4IP() {
        try {
            Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                // 去除回环接口，子接口，未运行和接口
                if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                    continue;
                }
//                if (!netInterface.getDisplayName().contains("Intel") && !netInterface.getDisplayName().contains("Realtek")) {
//                    continue;
//                }

                Enumeration addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress ip = (InetAddress) addresses.nextElement();
                    if (ip != null) {
                        // ipv4
                        if (ip instanceof Inet4Address) {
                            return ip.getHostAddress();
                        }
                    }
                }
                break;
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] parseIP4Address(String addr) {
        String[] addrStr = addr.split("\\D+");
        int[] addrInt = new int[addrStr.length];
        for (int i = 0; i < addrStr.length; i++) {
            addrInt[i] = Integer.parseInt(addrStr[i]);
        }
        return parseIP4Address(addrInt);
    }

    private static byte[] parseIP4Address(int[] addr) {
        if (addr.length > 4){
            throw new IllegalArgumentException("IP地址应为4个整数");
        }
        byte[] ip = new byte[4];
        for (int i = 0; i < addr.length; i++) {
            if (addr[i] < 0 || addr[i] > 255){
                throw new IllegalArgumentException("IP地址应为0至255的整数");
            }
            ip[i] = (byte) addr[i];
        }
        return ip;
    }
}
